package com.wosiliujing.learning.mobile;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.wosiliujing.learning.service.SecurityUserDetailService;
import com.wosiliujing.learning.validator.SocialParams;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;

/****
 * 手机登录校验逻辑
 * @author 刘靖
 * @date 2019/9/25 10:18
 */
@Slf4j
public class MobileAuthenticationProvider implements AuthenticationProvider {
    private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
    private UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();

    @Getter
    @Setter
    private SecurityUserDetailService userDetailService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken)authentication;
        String principle = mobileAuthenticationToken.getPrincipal().toString();
        SocialParams socialParams = JSONUtil.toBean(principle,SocialParams.class);
        UserDetails userDetails = userDetailService.loadUserBySocial(socialParams);
        if (ObjectUtil.isEmpty(userDetails)) {
            log.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(messages.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.noopBindAccount",
                    "Noop Bind Account"));
        }
        userDetailsChecker.check(userDetails);
        MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationToken.setDetails(mobileAuthenticationToken.getDetails());
        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        //只支持MobileAuthenticationToken
        return MobileAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
